package com.hannesdorfmann.mosby3.mvi.integrationtest.lifecycle.fraction.childfraction;

import com.hannesdorfmann.mosby3.mvi.MviFractionAbility;
import com.hannesdorfmann.mosby3.mvi.integrationtest.ResourceTable;
import com.hannesdorfmann.mosby3.mvi.integrationtest.lifecycle.LifecycleTestPresenter;
import com.hannesdorfmann.mosby3.mvi.integrationtest.lifecycle.LifecycleTestView;
import com.hannesdorfmann.mosby3.mvi.integrationtest.slice.MviLifecycleChildFractionAbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;

import java.util.Optional;

public class MviLifecycleChildFractionAbility extends MviFractionAbility<LifecycleTestView, LifecycleTestPresenter> implements LifecycleTestView {

    private static final String TAG ="FragmetnTag";
    public LifecycleTestPresenter presenter;
    public static int createPresenterInvokations = 0;
    private static volatile MviLifecycleChildFractionAbility currentInstance;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
//        super.setMainRoute(MviLifecycleChildFractionAbilitySlice.class.getName());
        super.setUIContent(ResourceTable.Layout_ability_child_mvi_container);
        currentInstance = getInstance();
    }

    public static MviLifecycleChildFractionAbility getInstance(){
        if(MviLifecycleChildFractionAbility.currentInstance == null){
            MviLifecycleChildFractionAbility.currentInstance = new MviLifecycleChildFractionAbility();
        }
        return  MviLifecycleChildFractionAbility.currentInstance;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public ContainerMviLifecycleFraction getFragment(){
        Optional<Fraction> fractionOptional = currentInstance.getFractionManager().getFractionByTag(TAG);
        return (ContainerMviLifecycleFraction) fractionOptional.get();
    }


    @Override protected void onStop() {
        super.onStop();
        System.err.println(getClass().getSimpleName()+ " onDestroy() " + this);
    }

    @Override public LifecycleTestPresenter createPresenter() {
        createPresenterInvokations++;
        presenter = new LifecycleTestPresenter();
        System.err.println(getClass().getSimpleName()+ " createPresenter() " + this + " " + presenter);
        return presenter;
    }

    public static void pressBackButton() {
        currentInstance.getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override public void run() {
                currentInstance.onBackPressed();
            }
        });
    }
}
